package cn.toma.common.qiniu;

import cn.toma.common.utils.StringUtils;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.storage.model.FileListing;
import com.qiniu.util.Auth;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author zqx
 * @version 1.0.0
 * @ClassName QiNiuUpload.java
 * @Description
 * @createTime 2019年10月15日 09:42:00
 */
@Data
@Slf4j
@Component
@ConfigurationProperties(prefix = "qiniu")
public class QiNiuUpload
{

	private String accessKey;
	private String secretKey;
	private String bucket;
	private String domainOfBucket;


	private String upToken;

	private UploadManager getUploadManager(String key)
	{
		Configuration cfg = new Configuration(Region.region2());
		Auth auth = Auth.create(accessKey, secretKey);
		if (StringUtils.isNotEmpty(key)) {
			upToken = auth.uploadToken(bucket, key);
		}
		else {
			upToken = auth.uploadToken(bucket);
		}

		UploadManager uploadManager = new UploadManager(cfg);

		return uploadManager;
	}

	public String uploadMultipartFile(MultipartFile file, String key)
	{
		//把文件转化为字节数组
		InputStream is = null;
		ByteArrayOutputStream bos = null;
		try {
			is = file.getInputStream();
			bos = new ByteArrayOutputStream();
			byte[] b = new byte[1024];
			int len = -1;
			while ((len = is.read(b)) != -1) {
				bos.write(b, 0, len);
			}
			byte[] uploadBytes = bos.toByteArray();

			String fileName = file.getOriginalFilename();
			// 指定要上传到 COS 上的路径
			String uuidFileName = UUID.randomUUID() + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
			String qiniuName = key + "/" + uuidFileName;
			UploadManager uploadManager = getUploadManager(qiniuName);
			Response response = uploadManager.put(uploadBytes, qiniuName, upToken);
			DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
			//key 文件名
			log.info("七牛云上传:{}", putRet.key);
			log.info("完整外链:{}", domainOfBucket + putRet.key);
			//hash 七牛返回的文件存储的地址，可以使用这个地址加七牛给你提供的前缀访问到这个视频
			log.info("七牛云上传Hash:{}", putRet.hash);
			return domainOfBucket + putRet.key;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * @param prefix    文件名前缀
	 * @param delimiter 指定目录分隔符，列出所有公共前缀（模拟列出目录效果）。缺省值为空字符串
	 * @param limit     每次迭代的长度限制，最大1000，推荐值 1000
	 * @return
	 */
	public FileListing getFileList(Integer limit, String prefix, String delimiter,String marker) throws QiniuException
	{
		Configuration cfg = new Configuration(Region.region2());
		Auth auth = Auth.create(accessKey, secretKey);
		BucketManager bucketManager = new BucketManager(auth, cfg);
		//列举空间文件列表
		FileListing fileListing = bucketManager.listFiles(bucket, prefix, marker, limit, delimiter);
		return fileListing;
	}


}
